// ==UserScript==
// @name         详情页获取
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  详情页获取并插入数据库
// @author       JFeng
// @require      https://cdn.bootcss.com/jquery/3.4.1/jquery.js
// @match        https://sellercentral.amazon.com/merchandising-new/view/*
// @match        https://sellercentral.amazon.com/merchandising-new/view*
// @match        *://sellercentral.amazon.com/merchandising-new/view/*
// @grant        none
// @icon         https://img2.baidu.com/it/u=3337194467,672949329&fm=26&fmt=auto&gp=0.jpg
// ==/UserScript==

(function () {
    'use strict';

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function uuid() {
        let s = [];
        let hexDigits = "0123456789abcdef";
        for (let i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        return s.join("").replace(/-/g, '');
    }


    function formatDate(date) {
        let y = date.getFullYear();
        let m = date.getMonth() + 1;
        m = m < 10 ? '0' + m : m;
        let d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        return y + '-' + m + '-' + d;
    }

    window.onload = async function () {
        /**
         * 向数据库插入数据
         * */
        function save2mysql(table, pageData) {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'http://amzapi.hieyoung.com:8281/records/' + table,
                headers: { 'Authorization': 'Basic aHl5OmhPOHVJRDNnZTNwbnJ2WXo2NXoz' },
                data: pageData,
                success: function (result) {
                    $("#smui-root > div.view-page > div > div.view-header.bg-white.px-32.py-16.mb-16.sticky > div > div.d-flex.ai-center.left > div.fs-24.lh-28.max-w-640").after("<b style='color:#50A10F;'>（更新到服务器成功）</b>");
                },
                error: function (xhr, status, error) {
                    $("#smui-root > div.view-page > div > div.view-header.bg-white.px-32.py-16.mb-16.sticky > div > div.d-flex.ai-center.left > div.fs-24.lh-28.max-w-640").after("<b style='color:#AC2306;'>（保存失败）</b>");
                },
            });
        }

        let array = $('#smui-root > div.view-page > div > div.px-32.pt-10.pb-32 > div > div.table-container > kat-table > kat-table-body > kat-table-row > kat-table-cell.create-or-edit-config-table-deal-price-cell > div > div');
        for (let index = 0; index < array.length; index++) {
            let element = array[index];
            let datetime = $('#smui-root > div.view-page > div > div.view-content.align-items-top.jc-space-between.px-32 > div > div.table-container.mt-24.w-780 > kat-table > kat-table-body > kat-table-row:nth-child(3) > kat-table-cell:nth-child(2)').text()

            let formatting = []
            if (/.*[\u4e00-\u9fa5]+.*$/.test(datetime)) {
                formatting[0] = datetime.split(" ")[0]
                formatting[1] = datetime.split(" ")[4]
            } else {
                formatting[0] = formatDate(new Date(datetime.split("-")[0]))
                formatting[1] = formatDate(new Date(datetime.split("-")[1]))
            }

            let strArray = $("#partner-switcher > button").text().split(" | ");

            let pageData = {
                'id': uuid(),
                'store_name': $("#partner-switcher > button").text(),
                'internal_description': $('#smui-root > div.view-page > div > div.view-content.align-items-top.jc-space-between.px-32 > div > div.table-container.mt-24.w-780 > kat-table > kat-table-body > kat-table-row:nth-child(1) > kat-table-cell:nth-child(2) > span').text(),
                'type_and_duration': $('#smui-root > div.view-page > div > div.view-content.align-items-top.jc-space-between.px-32 > div > div.table-container.mt-24.w-780 > kat-table > kat-table-body > kat-table-row:nth-child(2) > kat-table-cell:nth-child(2) > div > div.d-inline-block.ml-1.color-black').text(),
                'date': datetime,
                'deal_fee': $('#smui-root > div.view-page > div > div.view-content.align-items-top.jc-space-between.px-32 > div > div.table-container.mt-24.w-780 > kat-table > kat-table-body > kat-table-row:nth-child(4) > kat-table-cell:nth-child(2) > div').text(),
                'created_time': new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " "),
                "asin": $("#smui-root > div.view-page > div > div.px-32.pt-10.pb-32 > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + (index + 1) + ") > kat-table-cell:nth-child(1) > div > div > div.d-inline-block.ml-14 > div:nth-child(2)").text(),
                "sku": $("#smui-root > div.view-page > div > div.px-32.pt-10.pb-32 > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + (index + 1) + ") > kat-table-cell:nth-child(1) > div > div > div.d-inline-block.ml-14 > div:nth-child(3)").text(),
                "promotion_price": $(element).text(),
                "price": $("#smui-root > div.view-page > div > div.px-32.pt-10.pb-32 > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + (index + 1) + ") > kat-table-cell:nth-child(3)").text(),
                "merchandise_sold": $("#smui-root > div.view-page > div > div.px-32.pt-10.pb-32 > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + (index + 1) + ") > kat-table-cell:nth-child(4) > div:nth-child(1)").text(),
                "merchandise_sold_one": $("#smui-root > div.view-page > div > div.px-32.pt-10.pb-32 > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + (index + 1) + ") > kat-table-cell:nth-child(4) > div.color-smui-dark-grey.fs-12").text(),
                "page_view": $("#smui-root > div.view-page > div > div.px-32.pt-10.pb-32 > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + (index + 1) + ") > kat-table-cell.text-align-right.fs-14 > div:nth-child(1)").text(),
                "percent_conversion": $("#smui-root > div.view-page > div > div.px-32.pt-10.pb-32 > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + (index + 1) + ") > kat-table-cell.text-align-right.fs-14 > div.color-smui-dark-grey.fs-12").text(),
                "start_date": formatting[0],
                "end_date": formatting[1],
                "account": strArray[0],
                "site": strArray[1],
            }
            
            save2mysql('amazon_home', pageData);

            await sleep(1000)
        }
    };
})();